<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>电力设备智能管理系统登录</span>
        </div>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="0px">
        <el-form-item prop="name">
          <el-input v-model="loginForm.name" placeholder="请输入用户名" :prefix-icon="UserIcon" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" :prefix-icon="Lock" @keyup.enter="handleLogin" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin" style="width: 100%;">登录</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="text" @click="$router.push('/register')" style="width: 100%; text-align: center;">没有账号？去注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '@/stores/modules/auth';

const router = useRouter();
const store = useAuthStore();
const loginFormRef = ref(null);
const loading = ref(false);

// 初始化登录表单时，从 Store 中获取 name 和 password
const loginForm = reactive({
  name: store.name,
  password: store.password
});

const rules = reactive({
  name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
});

const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      store.login(loginForm)
        .then((response) => {
          ElMessage.success('登录成功');
          router.push('/dashboard');
        })
        .catch((error) => {
          ElMessage.error('登录失败，请检查用户名和密码');
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      ElMessage.error('表单验证失败，请检查输入');
    }
  });
};
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f2f5, #d2d6d9);

  .login-card {
    width: 400px;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

    .card-header {
      text-align: center;
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 20px;
    }
  }
}
</style>
